/*
 * PhysicalDAO.java
 *
 * Created on March 28, 2007, 10:07 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.samlam;

import java.sql.*;

/**
 * Extends the FeeDAO and handles database interaction for Physical revenue source objects
 * @author Nick
 */
public abstract class PhysicalDAO extends ProductDAO{
    
    private static PhysicalDAO instance;
    /** Creates a new instance of PhysicalDAO */
    protected PhysicalDAO() {
        super();
    }
    
    //Singleton pattern
   /* public static synchronized PhysicalDAO getInstance() {
        if (instance == null) {
            instance = new PhysicalDAO();
        }
        return instance;
    }*/
    
    /////////////////////////////////
    ///   CREATE
    
    /**
     * There's no need for two creates because we don't need
     * a connection to create BOs.  We run the insert statement
     * later, when it get's saved for the first time.
     */
    public Physical create() {
        Physical physical = null;
        try{
            String id = GUID.generate();
            physical = new Physical(id);
            Cache cache = Cache.getInstance();
            cache.put(physical.getId(), physical);
            
        }catch(Exception e){
            e.printStackTrace();
        }
        return (Physical)physical;
    }
    
    
    /////////////////////////////////////
    ///   READ
    
    /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     */
    public synchronized Physical read(String id) throws DataException {
        // check to see if id in the cache
        Physical physical = (Physical)Cache.getInstance().get(id);
        if(physical != null){
            // if so, return it immediately
            return (Physical)physical;
        }
        
        
        
        Connection conn = null;
        try {
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            // call read with a connection (the other read method in this class)
            physical = read(id, conn);
            
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
            
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
            
        }catch (SQLException e) {
            // rollback
            try{
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch(SQLException e2){
                throw new DataException("Big error: could not even release the connection", e2);
            }catch (ConnectionPoolException e3){
                throw new DataException("Could not get a connection to the database.");
                
            }
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        
        // return object
        return physical;
    }
    
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     */
    public synchronized Physical read(String id, Connection conn) throws SQLException, DataException {
        // check again if the id is in the cache, and if so,
        // just get it from the cache.  we need to check again
        // because this method might be called directly from
        // another DAO rather than from read above.
        Physical physical = (Physical)Cache.getInstance().get(id);
        if(physical != null){
            return physical;
        }
        // if not in the cache, get a result set from
        // a SELECT * FROM table WHERE id=guid
        //query the database
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM Physical WHERE physicalid = '"+ id + "'");
        
        
        if (rs.next()) {
        //call sets from the result set
        physical.setId(rs.getString("id"));
        physical.setSerialNumber(rs.getString("serialNumber"));
        physical.setShelflocation(rs.getString("shelfLocation"));
        physical.setSaleorRent(rs.getBoolean("saleOrRent"));
        physical.setNewOrUsed(rs.getBoolean("newOrUsed"));
        physical.setDatePurchased(rs.getString("datePurchased"));
        physical.setStoreID(rs.getString("storeID"));
        physical.setConceptualID(rs.getString("conceptualID"));
        Cache.getInstance().put(physical.getId(), physical);
            try {
                super.read(rs.getString("id"), conn);
            } catch (ConnectionPoolException ex) {
                ex.printStackTrace();
            } catch (SQLException ex) {
                ex.printStackTrace();
            } catch (DataException ex) {
                ex.printStackTrace();
            }
        
        physical.setObjectAlreadyInDB(true);
        
        
        // save to the cache
        Cache.getInstance().touch(physical.getId());
        stmt.close();
        }else{
            throw new DataException("Object was not found in the database.");
            
        }
        // return the BO
        return physical;
    }
    
    //////////////////////////////////
    ///   UPDATE
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an object
     * into the database.
     */
    public synchronized void save(Product physical) throws DataException {
        Connection conn = null;
        try {
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            // call save with a connection (the other save method in this class)
            this.save((Physical)physical, conn);
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (ConnectionPoolException e4){
                throw new DataException("Could not get a connection to the database.");
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }
            
            throw new DataException("Could not retrieve record for id=" + physical.getId(), e);
        }
    }
    
    
    /**
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the PhysicalDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  object needs to be inserted or updated.
     */
    synchronized void save(Physical physical, Connection conn) throws SQLException, DataException {
        // check the dirty flag in the object.  if it is dirty,
        // run update or insert
        if (physical.isDirty()) {
            
            if (physical.isObjectAlreadyInDB() == true) {
                update(physical, conn);
            }else{
                insert(physical, conn);
            }
            try {
                super.save(physical, conn);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } catch (ConnectionPoolException ex) {
                ex.printStackTrace();
            } catch (DataException ex) {
                ex.printStackTrace();
            }
            // set the dirty flag to false now that we've saved it
            physical.setDirty(false);
            
        }
        
        // touch the cache for the object
        Cache.getInstance().touch(physical.getId());
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void update(Physical physical, Connection conn) throws SQLException, DataException {
        // do the update statement
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("UPDATE Physical set  physicalid='"+physical.getId()+"', serialnumber='"+physical.getSerialNumber()+"', shelflocation='"+physical.getShelflocation()+"', datepurchased='"+physical.getDatePurchased()+"', conceptualid='"+physical.getConceptualID()+"', storeid='"+physical.getStoreID()+"', saleorrent='"+physical.isSaleorRent()+"', neworused='"+physical.isNewOrUsed()+"' WHERE physicalid='"+physical.getId()+"'");
        stmt.close();
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void insert(Physical physical, Connection conn) throws SQLException, DataException {
        // do the insert SQL statement
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("INSERT INTO Physical VALUES ('"+physical.getId()+"', '"+physical.getSerialNumber()+"', '"+physical.getShelflocation()+"', '"+physical.getDatePurchased()+"', '"+physical.getConceptualID()+"', '"+physical.getStoreID()+"', '"+physical.isSaleorRent()+"', '"+physical.isNewOrUsed());
        stmt.close();
    }
    
    
    ////////////////////////////////////
    ///   DELETE
    // we are not supporting because we never want to delete the Physical from
    // our database.
    
    
    
    //////////////////////////////
    ///  SEARCH methods
    
    
}
